"""
客户相关路由
"""
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from datetime import datetime
from app.models import User
from app.services import CustomerService

# 创建蓝图
customer_bp = Blueprint('customer', __name__, url_prefix='/customer')

@customer_bp.route('/')
@login_required
def list_customers():
    """客户列表"""
    page = request.args.get('page', 1, type=int)
    per_page = 10
    customers = CustomerService.get_customers(page=page, per_page=per_page)
    sources = CustomerService.get_sources()
    categories = CustomerService.get_categories()
    locations = CustomerService.get_locations()
    
    # 获取总客户数用于分页计算
    total_customers = CustomerService.get_customer_count()
    
    # 计算总页数
    total_pages = (total_customers + per_page - 1) // per_page
    
    return render_template('customer_list.html', 
                          customers=customers, 
                          sources=sources,
                          categories=categories,
                          locations=locations,
                          page=page,
                          per_page=per_page,
                          total_pages=total_pages,
                          total_customers=total_customers)

@customer_bp.route('/create', methods=['GET', 'POST'])
@login_required
def create_customer():
    """创建客户"""
    if request.method == 'POST':
        name = request.form.get('name')
        category = request.form.get('category')
        category_other = request.form.get('category_other')
        location = request.form.get('location')
        location_other = request.form.get('location_other')
        source = request.form.get('source')
        source_other = request.form.get('source_other')
        province_id = request.form.get('province_id', type=int)
        city_id = request.form.get('city_id', type=int)
        district_id = request.form.get('district_id', type=int)
        address = request.form.get('address')
        
        success, message, customer = CustomerService.create_customer(
            name=name,
            category=category,
            category_other=category_other,
            location=location,
            location_other=location_other,
            source=source,
            source_other=source_other,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            address=address,
            manager_id=current_user.id
        )
        
        if success:
            flash(message)
            return redirect(url_for('customer.list_customers'))
        else:
            flash(message)
            return redirect(url_for('customer.create_customer'))
    
    # 获取表单所需的数据
    categories = CustomerService.get_categories()
    locations = CustomerService.get_locations()
    sources = CustomerService.get_sources()
    provinces = CustomerService.get_provinces()
    
    # 预先生成客户编号，以便在表单中显示
    from app.models.customer import Customer
    preview_customer_number = Customer.generate_customer_number()
    
    return render_template('customer_form.html', 
                          categories=categories,
                          locations=locations,
                          sources=sources,
                          provinces=provinces,
                          preview_customer_number=preview_customer_number)

@customer_bp.route('/<int:customer_id>')
@login_required
def view_customer(customer_id):
    """查看客户详情"""
    customer = CustomerService.get_customer(customer_id)
    
    if not customer:
        flash('您没有权限查看此客户')
        return redirect(url_for('customer.list_customers'))
    
    # 获取客户联系人
    contacts = CustomerService.get_customer_contacts(customer_id)
    
    # 获取跟进记录
    follow_ups = CustomerService.get_customer_follow_ups(customer_id)
    
    return render_template('customer_detail.html', customer=customer, contacts=contacts, follow_ups=follow_ups)

@customer_bp.route('/<int:customer_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_customer(customer_id):
    """编辑客户"""
    customer = CustomerService.get_customer(customer_id)
    
    if not customer:
        flash('您没有权限编辑此客户')
        return redirect(url_for('customer.list_customers'))
    
    if request.method == 'POST':
        name = request.form.get('name')
        category = request.form.get('category')
        category_other = request.form.get('category_other')
        location = request.form.get('location')
        location_other = request.form.get('location_other')
        source = request.form.get('source')
        source_other = request.form.get('source_other')
        province_id = request.form.get('province_id', type=int)
        city_id = request.form.get('city_id', type=int)
        district_id = request.form.get('district_id', type=int)
        address = request.form.get('address')
        
        success, message = CustomerService.update_customer(
            customer_id=customer_id,
            name=name,
            category=category,
            category_other=category_other,
            location=location,
            location_other=location_other,
            source=source,
            source_other=source_other,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            address=address,
            manager_id=current_user.id
        )
        
        if success:
            flash(message)
            return redirect(url_for('customer.view_customer', customer_id=customer_id))
        else:
            flash(message)
            return redirect(url_for('customer.edit_customer', customer_id=customer_id))
    
    # 获取表单所需的数据
    categories = CustomerService.get_categories()
    locations = CustomerService.get_locations()
    sources = CustomerService.get_sources()
    provinces = CustomerService.get_provinces()
    
    # 获取当前城市的区县列表
    cities = []
    districts = []
    if customer.city_id:
        cities = CustomerService.get_cities(customer.province_id)
    if customer.district_id:
        districts = CustomerService.get_districts(customer.city_id)
    
    return render_template('customer_form.html', 
                          customer=customer,
                          categories=categories,
                          locations=locations,
                          sources=sources,
                          provinces=provinces,
                          cities=cities,
                          districts=districts)

@customer_bp.route('/<int:customer_id>/delete', methods=['POST'])
@login_required
def delete_customer(customer_id):
    """删除客户"""
    success = CustomerService.delete_customer(customer_id)
    
    if success:
        flash('客户删除成功')
    else:
        flash('您没有权限删除此客户')
    
    return redirect(url_for('customer.list_customers'))

@customer_bp.route('/test/generate_number')
def test_generate_customer_number():
    """测试客户编号生成"""
    from app.models.customer import Customer
    customer_number = Customer.generate_customer_number()
    return jsonify({'customer_number': customer_number})

@customer_bp.route('/<int:customer_id>/contact/create', methods=['GET', 'POST'])
@login_required
def create_contact(customer_id):
    """创建客户联系人"""
    customer = CustomerService.get_customer(customer_id)
    
    if not customer:
        flash('您没有权限为此客户创建联系人')
        return redirect(url_for('customer.list_customers'))
    
    if request.method == 'POST':
        name = request.form.get('name')
        position = request.form.get('position')
        phone = request.form.get('phone')
        email = request.form.get('email')
        is_primary = True if request.form.get('is_primary') else False
        
        contact = CustomerService.create_contact(
            customer_id=customer_id,
            name=name,
            position=position,
            phone=phone,
            email=email,
            is_primary=is_primary
        )
        
        flash('联系人创建成功')
        return redirect(url_for('customer.view_customer', customer_id=customer_id))
    
    return render_template('contact_form.html', customer=customer)

@customer_bp.route('/<int:customer_id>/followup/create', methods=['GET', 'POST'])
@login_required
def create_follow_up(customer_id):
    """创建跟进记录"""
    customer = CustomerService.get_customer(customer_id)
    
    if not customer:
        flash('您没有权限为此客户创建跟进记录')
        return redirect(url_for('customer.list_customers'))
    
    if request.method == 'POST':
        method = request.form.get('method')
        content = request.form.get('content')
        result = request.form.get('result')
        next_followup_time = request.form.get('next_followup_time')
        
        success, message, follow_up = CustomerService.create_follow_up(
            customer_id=customer_id,
            method=method,
            content=content,
            result=result,
            next_followup_time=next_followup_time
        )
        
        if success:
            flash(message)
            return redirect(url_for('customer.view_customer', customer_id=customer_id))
        else:
            flash(message)
            return redirect(url_for('customer.create_follow_up', customer_id=customer_id))
    
    return render_template('followup_form.html', customer=customer)

@customer_bp.route('/contact/<int:contact_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_contact(contact_id):
    """编辑客户联系人"""
    contact = CustomerService.get_contact(contact_id)
    
    if not contact:
        flash('联系人不存在')
        return redirect(url_for('customer.list_customers'))
    
    customer = CustomerService.get_customer(contact.customer_id)
    
    if not customer:
        flash('您没有权限编辑此联系人')
        return redirect(url_for('customer.list_customers'))
    
    if request.method == 'POST':
        name = request.form.get('name')
        position = request.form.get('position')
        phone = request.form.get('phone')
        email = request.form.get('email')
        is_primary = True if request.form.get('is_primary') else False
        
        success, message = CustomerService.update_contact(
            contact_id=contact_id,
            name=name,
            position=position,
            phone=phone,
            email=email,
            is_primary=is_primary
        )
        
        if success:
            flash(message)
            return redirect(url_for('customer.view_customer', customer_id=customer.id))
        else:
            flash(message)
            return redirect(url_for('customer.edit_contact', contact_id=contact_id))
    
    return render_template('contact_form.html', customer=customer, contact=contact)

@customer_bp.route('/followup/<int:followup_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_follow_up(followup_id):
    """编辑跟进记录"""
    follow_up = CustomerService.get_follow_up(followup_id)
    
    if not follow_up:
        flash('跟进记录不存在')
        return redirect(url_for('customer.list_customers'))
    
    customer = CustomerService.get_customer(follow_up.customer_id)
    
    if not customer:
        flash('您没有权限编辑此跟进记录')
        return redirect(url_for('customer.list_customers'))
    
    if request.method == 'POST':
        method = request.form.get('method')
        content = request.form.get('content')
        result = request.form.get('result')
        next_followup_time = request.form.get('next_followup_time')
        
        success, message = CustomerService.update_follow_up(
            followup_id=followup_id,
            method=method,
            content=content,
            result=result,
            next_followup_time=next_followup_time
        )
        
        if success:
            flash(message)
            return redirect(url_for('customer.view_customer', customer_id=customer.id))
        else:
            flash(message)
            return redirect(url_for('customer.edit_follow_up', followup_id=followup_id))
    
    return render_template('followup_form.html', customer=customer, followup=follow_up)

@customer_bp.route('/api/regions/<int:province_id>/cities')
@login_required
def get_cities(province_id):
    """获取指定省份的城市列表API"""
    cities = CustomerService.get_cities(province_id)
    return jsonify(cities)

@customer_bp.route('/api/regions/<int:city_id>/districts')
@login_required
def get_districts(city_id):
    """获取指定城市的区县列表API"""
    districts = CustomerService.get_districts(city_id)
    return jsonify(districts)